﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using DevComponents.DotNetBar;
using ESRI.ArcGIS.Carto;
using ESRI.ArcGIS.Geodatabase;
using ESRI.ArcGIS.Geometry;
using PlanningGIS.Util;
using PlanningGIS.ArcGIS;
using PlanningGIS.ArcGIS.Custom;
using PlanningGIS.Engine.Controls;
using PlanningGIS.Win.Controls;
using PlanningGIS.MapSheet;

namespace PlanningGIS.MapSheet
{
    /// <summary>
    /// 图幅操作：创建图幅
    /// </summary>
    public partial class FrmMapSheet : Office2007Form
    {
        /// <summary>
        /// 构造函数
        /// </summary>
        public FrmMapSheet()
        {
            InitializeComponent();
        }
        /// <summary>
        /// 加载窗体
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void FrmMapSheet_Load(object sender, EventArgs e)
        {
            Init();
        }

        /// <summary>
        /// 初始化
        /// </summary>
        private void Init()
        {
            cmbSizeType.DisplayMember = "Name";
            cmbSizeType.ValueMember = "Value";
            cmbSizeType.DataSource = SheetHelper.Config.SizeTypes;
            cmbSizeType.SelectedIndex = 0;
            
            cmbScale.DisplayMember = "Display";
            cmbScale.ValueMember = "Value";
            cmbScale.DataSource = SheetHelper.Config.ScaleTypes;
            cmbScale.SelectedIndex = 0;
            rdoFile.Checked = true;
        }

        /// <summary>
        /// 图幅图层
        /// </summary>
        private IFeatureClass tufuFeatureClass = null;

        /// <summary>
        /// 范围图层
        /// </summary>
        private IFeatureClass fullFeatureClass = null;

        /// <summary>
        /// 选择要创建到的图幅文件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSheetName_Click(object sender, EventArgs e)
        {
            OpenDataDialog frm = new OpenDataDialog();
            frm.Activate();
            frm.MultiSelect = false;
            if (frm.ShowDialog(this) == System.Windows.Forms.DialogResult.OK)
            {
                txtSheetName.Text = "";
                tufuFeatureClass = null;
                List<FeatureClassNode> pLayers = frm.GetSelectNode<FeatureClassNode>();
                if (pLayers != null && pLayers.Count > 0)
                {
                    FeatureClassNode lyrnode = pLayers[0];
                    IDataset ds = lyrnode.Open();
                    if (ds is IFeatureClass)
                    {
                        IFeatureClass f = ds as IFeatureClass;
                        if (f.ShapeType == ESRI.ArcGIS.Geometry.esriGeometryType.esriGeometryPolygon)
                        {
                            tufuFeatureClass = f;
                            txtSheetName.Text = frm.FullName;
                            SetFields(f);
                            return;
                        }
                    }
                }
                MsgHelper.ShowInfomationMsgbox("请选择有效的图幅数据文件（面数据）");
            }
        }

        /// <summary>
        /// 设置图号字段
        /// </summary>
        /// <param name="featureClass"></param>
        private void SetFields(IFeatureClass featureClass)
        {
            cmbFieldName.Items.Clear();
            if (featureClass == null) return;
            IFields fds = featureClass.Fields;
            int count = fds.FieldCount;
            for (int i = 0; i < count; i++)
            {
                IField fd = fds.get_Field(i);
                if (fd.Type == esriFieldType.esriFieldTypeString && fd.Editable)
                {
                    cmbFieldName.Items.Add(fd.Name);
                }
            }
            if (cmbFieldName.Items.Count > 0)
                cmbFieldName.SelectedIndex = 0;
        }
        
        /// <summary>
        /// 选择创建的图幅要满足的范围的空间数据文件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnFullName_Click(object sender, EventArgs e)
        {
            OpenDataDialog frm = new OpenDataDialog();
            frm.Activate();
            frm.MultiSelect = false;
            if (frm.ShowDialog(this) == System.Windows.Forms.DialogResult.OK)
            {
                txtFullName.Text = "";
                fullFeatureClass = null;
                List<FeatureClassNode> pLayers = frm.GetSelectNode<FeatureClassNode>();
                if (pLayers != null && pLayers.Count > 0)
                {
                    FeatureClassNode lyrnode = pLayers[0];
                    IDataset ds = lyrnode.Open();
                    if (ds is IFeatureClass)
                    {
                        fullFeatureClass = ds as IFeatureClass;
                        txtFullName.Text = frm.FullName;
                        return;
                    }
                }
                MsgHelper.ShowInfomationMsgbox("请选择有效的图幅数据文件（面数据）");
            }
            
        }

        /// <summary>
        /// 范围选择改变
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void rdoExtent_CheckedChanged(object sender, EventArgs e)
        {
            txtXMax.Enabled = rdoExtent.Checked;
            txtXMin.Enabled = rdoExtent.Checked;
            txtYMax.Enabled = rdoExtent.Checked;
            txtYMin.Enabled = rdoExtent.Checked;

            txtFullName.Enabled = !rdoExtent.Checked;
            chkRemove.Enabled = !rdoExtent.Checked;
            btnFullName.Enabled = !rdoExtent.Checked;
        }
        
        /// <summary>
        /// 创建
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnCreate_Click(object sender, EventArgs e)
        {
            if (tufuFeatureClass == null)
            {
                MsgHelper.ShowInfomationMsgbox(this,"请先选择要创建的图幅文件");
                return;
            }            
            int ftcount = tufuFeatureClass.FeatureCount(null);
            if (ftcount > 0)
            {
                DialogResult dlgrst = MsgHelper.ShowYesNoCancelQueryMsgbox("该图幅文件中已经存在数据，是否删除？");
                if (dlgrst == System.Windows.Forms.DialogResult.Yes)
                {
                    FeatureClassHelper.DeleteSearchedRows(tufuFeatureClass as ITable, "");
                }
                else if (dlgrst == System.Windows.Forms.DialogResult.Cancel)
                    return;
            }
            SheetScale scaletype = (SheetScale)cmbScale.SelectedItem;
            Progressor prg = new Progressor() { ProgressBar = progress };
            IMapsheet sheet = new LowerLeftMapsheet()
            {
                SizeString = cmbSizeType.SelectedValue.ToString(),
                UnitValue = SheetHelper.Config.UnitValue,
                _Progressor = new Progressor() { ProgressBar = progress }
            };
            if (chkKZ.Checked)
            {
                sheet.OffsetLen = txtDis.Value;
            }
            if (rdoExtent.Checked)
            {
                if (string.IsNullOrEmpty(txtYMin.Text) || string.IsNullOrEmpty(txtYMax.Text) ||
                    string.IsNullOrEmpty(txtXMin.Text) || string.IsNullOrEmpty(txtXMax.Text))
                {
                    MsgHelper.ShowInfomationMsgbox("请先输入有效的范围");
                    return;
                }
                try
                {
                    IEnvelope env = new ESRI.ArcGIS.Geometry.Envelope() as IEnvelope;
                    env.XMax = double.Parse(txtXMax.Text);
                    env.XMin = double.Parse(txtXMin.Text);
                    env.YMax = double.Parse(txtYMax.Text);
                    env.YMin = double.Parse(txtYMin.Text);
                    sheet.CreateMapSheet(env, tufuFeatureClass, cmbFieldName.Text, scaletype);
                }
                catch (Exception ex)
                {
                    MsgHelper.ShowInfomationMsgbox(ex.Message);
                    return;
                }
            }
            else
            {
                try
                {
                    if (fullFeatureClass == null)
                    {
                        MsgHelper.ShowInfomationMsgbox("请先选择图幅范围文件");
                        return;
                    }
                    int count = fullFeatureClass.FeatureCount(null);
                    if (count == 0)
                    {
                        MsgHelper.ShowInfomationMsgbox("图幅范围文件没有数据，请重新选择");
                        return;
                    }
                    else if (count == 1)
                    {
                        IFeatureCursor cur = fullFeatureClass.Search(null, false);
                        IFeature feature = cur.NextFeature();
                        sheet.CreateMapSheet(feature.Shape, tufuFeatureClass, cmbFieldName.Text, scaletype, chkRemove.Checked);
                        Marshal.ReleaseComObject(cur);
                        cur = null;
                    }
                    else
                    {
                        sheet.CreateMapSheet(fullFeatureClass, tufuFeatureClass, cmbFieldName.Text, scaletype, chkRemove.Checked);
                    }
                    MsgHelper.ShowInfomationMsgbox(this, "图幅已创建完成");
                }
                catch (Exception ex)
                {
                    MsgHelper.ShowInfomationMsgbox(ex.Message);
                }
            }
        }

        #region 消息
        
        /// <summary>
        /// 设置监听消息
        /// </summary>
        /// <param name="message"></param>
        private delegate void SetTextCallback(string message);
        /// <summary>
        /// 
        /// </summary>
        /// <param name="msg"></param>
        private void SetMsg(string msg)
        {
            //if (lblMsg.InvokeRequired)
            //{
            //    SetTextCallback d = new SetTextCallback(SetMsg);
            //    lblMsg.Invoke(d, new object[] { msg });
            //}
            //else
            //{
            //    lblMsg.Text = msg;
            //}
        }

        /// <summary>
        /// 设置监听消息
        /// </summary>
        /// <param name="number"></param>
        private delegate void SetProgressCallback(int number);

        /// <summary>
        /// 
        /// </summary>
        /// <param name="total"></param>
        private void SetTotal(int total)
        {
            if (progress.InvokeRequired)
            {
                SetProgressCallback d = new SetProgressCallback(SetTotal);
                progress.Invoke(d, new object[] { total });
            }
            else
            {
                progress.Maximum = total;
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="index"></param>
        private void SetIndex(int index)
        {
            if (progress.InvokeRequired)
            {
                SetProgressCallback d = new SetProgressCallback(SetIndex);
                progress.Invoke(d, new object[] { index });
            }
            else
            {
                progress.Value = index;
                progress.Text = index.ToString() + "/" + progress.Maximum.ToString();
            }
        }
        #endregion

        /// <summary>
        /// 退出
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void chkKZ_CheckedChanged(object sender, EventArgs e)
        {
            txtDis.Enabled = chkKZ.Checked;
            if (chkKZ.Checked)
            {
                chkRemove.Checked = false;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void chkRemove_CheckedChanged(object sender, EventArgs e)
        {
            if (chkRemove.Checked)
            {
                chkKZ.Checked = false;
            }
        }


    }
}
